package ort.test.oscache;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.json.JSONObject;

import com.opensymphony.oscache.base.AbstractCacheAdministrator;
import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.base.Config;
import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.base.persistence.PersistenceListener;
import com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener;
import com.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener;

@SuppressWarnings("unused")
public final class CacheManager extends AbstractCacheAdministrator {
    /**
     * 
     */
    private static final long serialVersionUID = 5537692306055621671L;
    private static CacheManager cacheManager = null;
    public static Properties tmpProp = new Properties();
    public Cache pagePoliceCache = null;

    private CacheManager(Properties p) {
        super(p);
        pagePoliceCache = new Cache(isMemoryCaching(), isUnlimitedDiskCache(),
                isOverflowPersistence(), isBlocking(), algorithmClass,
                cacheCapacity);
        try {
            PersistenceListener listener = new DiskPersistenceListener();
            listener.configure(new Config(tmpProp));
            pagePoliceCache.setPersistenceListener(listener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static CacheManager getInstance() {
        if (cacheManager == null) {
            synchronized (CacheManager.class) {

                InputStream is = null;
                try {
                    is = Thread.currentThread().getContextClassLoader()
                            .getResource("oscache.properties").openStream();
                    tmpProp.load(is);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (cacheManager == null) {
                    cacheManager = new CacheManager(tmpProp);
                }
            }
        }
        return cacheManager;
    }

    public synchronized void putInPagePoliceCache(String key, JSONObject value) {
        pagePoliceCache.putInCache(key, value);
    }

    public synchronized JSONObject getFromPagePoliceCache(String ownJID) {
        try {
            JSONObject result = (JSONObject) pagePoliceCache
                    .getFromCache(ownJID);
            return result;
        } catch (NeedsRefreshException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
